from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

from myapp.models import User,Goods,UserFlow
from myapp.myser import *
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket

import uuid
import pymongo
# 分页

from rest_framework import pagination

class PaginationGoods(pagination.PageNumberPagination):
    # 在不传入page_size参数时的默认长度
    page_size = 5
    # 设定在使用url传递参数时每页展示数量的参数名
    page_size_query_param = 'size'
    # 设定在使用url传递参数时展示的页数的参数名
    page_query_param = 'page'
    # 设定每页的最大展示数量
    max_page_size = 5

# 装饰器
def my_decorator(func):
    def wrapper(request, *args, **kwargs):
        print('id校验中......')
        uid = request.GET.get('uid')
        jwt_str = request.GET.get('jwt', None)
        decode_jwt = jwt.decode(jwt_str, '446652', algorithms=['HS256'])
        if str(decode_jwt['uid']) != str(uid):
            # 请求的uid与加密jwt不相同,判定不是本人,终止操作
            res = {}
            res['code'] = 301
            res['message'] = '检测到id异常,已终止密钥获取,请检查您的账号状态'
            return Response(res)
        print('id校验通过,开始获取密钥')
        return func(request, *args)    
    return wrapper
# 类装饰器调用
from django.utils.decorators import method_decorator



# 七牛云密钥接口
from qiniu import Auth

class NewQiNiu(APIView):
    @method_decorator(my_decorator)
    def get(self, request):
        
        # 圣光明一个密钥对象
        q = Auth('FrZcNsgzftewSOxOugEoFgQq93VQhHDv_UMAJ0P2','30fYKbfMJEHaa9iBgvWHK0JdUyX_CMEtelS_RwXx')
        # 生成令牌
        token = q.upload_token('my-data-for-fcg',expires=30000)
        
        return Response({'uptoken':token})
    

        
from django.utils.deprecation import MiddlewareMixin

# 定义中间件类
class MyMiddleWare(MiddlewareMixin):
    # 请求之前进行身份验证
    def process_request(self, request):
        uid = request.GET.get('uid')
        jwt_str = request.GET.get('jwt', None)
        print(jwt_str)
        decode_jwt = jwt.decode(jwt_str, '446652', algorithms=['HS256'])
        if str(decode_jwt['uid']) != str(uid):
            # 请求的uid与加密jwt不相同,判定不是本人,终止操作
            return HttpResponse('你没有此账号的操作权限')
        pass
    def process_view(self, request, view_func,view_args,view_kwargs):
        pass
    def process_response(self, request, response):
        return response
    
    
    
# 导入bson
from bson import json_util as jsonb

cli = pymongo.MongoClient()
# 将tags存入mongo中
class InsertTags(APIView):
    
    def get(self,request):
        gid = request.GET.get('gid',None)
        tags = request.GET.get('tags',None)
        # 字符串转list
        tags = tags.split(',')
        # 建立数据库对象(如果没有此数据库，则自动创建)
        db = cli.md
        # 建立表对象(如果没有此表，则自动创建)
        table = db.mytag

        # 排重
        res = table.find({'gid':str(gid)}).count()

        if res > 0:
            return Response({'message':'标签已存在'})

        table.insert({'gid':str(gid),'tags':tags})
        return Response({'message':'入库成功'})
    
    
# 添加商品
class AddGoods(APIView):
    def get(self, request, *args, **kwargs):
        name = request.GET.get('name')
        desc = request.GET.get('desc')
        img = request.GET.get('img')
        video = request.GET.get('video')
        price = request.GET.get('price')
        
        goods = Goods.objects.filter(name=name).first()
        if goods:
            print(goods.id)
            return Response({'code':301,'message': '该商品已存在'})
        good = Goods(
            name=name,
            desc=desc,
            img=img,
            video=video,
            price=price)
        good.save()
        my_good = Goods.objects.filter(name=name).first()
        return Response({'code':200,'message': '创建成功','gid':my_good.id})

# 获取标签
class GetTags(View):

    def get(self,request):
        gid = request.GET.get('gid',None)
        print(gid)
        # 建立数据库对象
        db = cli.md
        # 建立表对象
        table = db.mytag
        # 查询数据
        res = table.find_one({"gid":str(gid)})
        return HttpResponse(jsonb.dumps(res,ensure_ascii=False))
    

# 获取商品
class GoodsList(ModelViewSet):
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    
    pagination_class = PaginationGoods
    
   
class GetFlow(APIView):
    def get(self, request):
        uid = request.GET.get('uid', None)
        flows = UserFlow.objects.filter(uid=uid)
        if flows:
            return Response({'code':200,'message': '已关注该商品','flow':1})
        
        else:
            return Response({'code':200,'message': '未关注该商品','flow':0})
        
r = redis.Redis()
class ChangeFlow(APIView):
    def get(self,request):
        uid = request.GET.get('uid', None)
        flow = request.GET.get('flow', None)
        gid = request.GET.get('gid', None)
        redis_time = request.GET.get('redis_time', None)
        redis_key = r.get("redis_time")
        if redis_key:
            
            return Response({'code':201,'message': '您的操作过于频繁,请稍后'})
        r.set("redis_time",'1')
        r.expire("redis_time",180)
        if flow=='true':
            new_flow = UserFlow()
            new_flow.uid = uid
            new_flow.gid = gid
            new_flow.save()
            
            good = Goods.objects.filter(id=gid).first()
            good.flow += 1
            good.save()
            return Response({'code':200,'message': '关注成功'})
        else:
            UserFlow.objects.filter(uid=uid).delete()
            
            good = Goods.objects.filter(id=gid).first()
            good.flow -= 1
            good.save()
            return Response({'code':200,'message': '关注取消'})
            
        
            
            
            
        